package com.north.light.libpermission.constant;

import android.text.TextUtils;
import android.util.Log;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * author:li
 * date:2022/8/19
 * desc:权限工具类
 */
public class PermissionReflex implements Serializable {

    private static final String TAG = PermissionReflex.class.getSimpleName();
    private ConcurrentMap<String, String> mPermissionMap = new ConcurrentHashMap<>();

    private static class SingleHolder implements Serializable {
        static PermissionReflex mInstance = new PermissionReflex();
    }

    public static PermissionReflex getInstance() {
        return SingleHolder.mInstance;
    }

    public PermissionReflex() {
        //通过反射获取所有权限列表声明
        initPermissionByReflex();
    }

    private void initPermissionByReflex() {
        try {
            mPermissionMap.clear();
            Class permissionReflex = Class.forName(Permission.class.getName());
            Field[] fields = permissionReflex.getDeclaredFields();
            for (Field field : fields) {
                String fieldName = field.getName();
                Object fieldNameObj = field.get(fieldName);
                if (fieldNameObj instanceof String) {
                    String fieldNameStr = (String) fieldNameObj;
                    Log.d(TAG, "initPermissionByReflex fieldNameStr: " + fieldNameStr + "\n" + "fieldName: " + fieldName);
                    if (!TextUtils.isEmpty(fieldNameStr) && !TextUtils.isEmpty(fieldName)) {
                        mPermissionMap.put(fieldNameStr, fieldName);
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "initPermissionByReflex error: " + e.getMessage());
        }
    }


    /**
     * 获取反射变量集合
     */
    public ConcurrentMap<String, String> getPermissionMap() {
        return mPermissionMap;
    }

    /**
     * 判断传入权限是否包含
     */
    public boolean containPermission(String permissions) {
        if (TextUtils.isEmpty(permissions)) {
            return false;
        }
        return mPermissionMap.containsKey(permissions);
    }

    public boolean containPermission(String... permission) {
        for (String str : permission) {
            boolean containRes = containPermission(str);
            if (!containRes) {
                return false;
            }
        }
        return true;
    }
    public boolean containPermission(List<String> permission) {
        for (String str : permission) {
            boolean containRes = containPermission(str);
            if (!containRes) {
                return false;
            }
        }
        return true;
    }
}
